export function initSpeedChart(canvas) {
    const ctx = canvas.getContext('2d');
    const STORAGE_KEY = 'speedChartData';
    
    // 从localStorage加载数据
    const loadStoredData = () => {
        try {
            const storedData = localStorage.getItem(STORAGE_KEY);
            if (storedData) {
                const parsedData = JSON.parse(storedData);
                return {
                    labels: parsedData.labels || [],
                    speeds: parsedData.speeds || [],
                    signals: parsedData.signals || [],
                    positions: parsedData.positions || [],
                    maxSpeed: parsedData.maxSpeed || 450
                };
            }
        } catch (error) {
            console.error('Error loading stored chart data:', error);
        }
        return {
            labels: [],
            speeds: [],
            signals: [],
            positions: [],
            maxSpeed: 450
        };
    };

    // 保存数据到localStorage
    const saveData = (data) => {
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify({
                labels: data.labels,
                speeds: data.speeds,
                signals: data.signals,
                positions: data.positions,
                maxSpeed: data.maxSpeed
            }));
        } catch (error) {
            console.error('Error saving chart data:', error);
        }
    };

    const storedData = loadStoredData();
    const chartData = {
        labels: storedData.labels,
        speeds: storedData.speeds,
        signals: storedData.signals,
        positions: storedData.positions,
        maxSpeed: storedData.maxSpeed,
        animationFrameId: null,
        baseXSpacing: (canvas.width - 70) / 50,  // 初始x轴间距（基于50个点的显示）
        minXSpacing: 0.1,  // 最小x轴间距
        hoveredPoint: null
    };

    // 添加鼠标事件监听
    function handleMouseMove(event) {
        const rect = canvas.getBoundingClientRect();
        const mouseX = event.clientX - rect.left;
        const mouseY = event.clientY - rect.top;
        const currentXSpacing = Math.max(
            chartData.minXSpacing,
            (canvas.width - 70) / chartData.speeds.length
        );

        // 查找最近的数据点
        let closestPoint = null;
        let minDistance = Infinity;

        chartData.speeds.forEach((speed, index) => {
            const x = 60 + (index * currentXSpacing);
            const y = canvas.height - 40 - (speed * (canvas.height - 50) / chartData.maxSpeed);
            const distance = Math.sqrt(Math.pow(x - mouseX, 2) + Math.pow(y - mouseY, 2));

            if (distance < 20 && distance < minDistance) {  // 20px 的检测范围
                minDistance = distance;
                closestPoint = index;
            }
        });

        chartData.hoveredPoint = closestPoint;
        drawChart();  // 重绘以显示工具提示
    }

    function handleMouseLeave() {
        chartData.hoveredPoint = null;
        drawChart();
    }

    canvas.addEventListener('mousemove', handleMouseMove);
    canvas.addEventListener('mouseleave', handleMouseLeave);

    function drawTooltip(index, x, y) {
        const speed = chartData.speeds[index];
        const time = chartData.labels[index];
        const signal = chartData.signals[index];
        const position = chartData.positions[index];

        // 绘制工具提示框
        ctx.save();
        ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
        ctx.strokeStyle = 'white';
        ctx.lineWidth = 1;
        ctx.roundRect(x + 10, y - 80, 200, 80, 5);
        ctx.fill();
        ctx.stroke();

        // 绘制文本
        ctx.fillStyle = 'white';
        ctx.font = '12px Arial';
        ctx.fillText(`时间: ${time}`, x + 20, y - 60);
        ctx.fillText(`速度: ${speed.toFixed(2)} km/h`, x + 20, y - 45);
        ctx.fillText(`信号: ${signal || 'N/A'}`, x + 20, y - 30);
        ctx.fillText(`位置: ${position || 'N/A'}`, x + 20, y - 15);
        ctx.restore();
    }

    function drawSignalMarker(index, x, y, signal) {
        if (!signal) return;

        // 绘制竖线
        ctx.beginPath();
        ctx.strokeStyle = '#FF4444';
        ctx.lineWidth = 2;
        ctx.setLineDash([4, 2]);
        ctx.moveTo(x, canvas.height - 40);
        ctx.lineTo(x, y - 30);
        ctx.stroke();
        ctx.setLineDash([]);

        // 绘制信号标注背景
        ctx.fillStyle = '#FF4444';
        ctx.beginPath();
        ctx.roundRect(x + 5, y - 45, 60, 20, 5);
        ctx.fill();

        // 绘制信号文本
        ctx.fillStyle = 'white';
        ctx.font = '12px Arial';
        ctx.fillText(signal, x + 10, y - 30);

        // 这里预留放置信号图片的位置
        // TODO: 后续添加信号图片
        // ctx.drawImage(signalImage, x + 5, y - 65, 20, 20);
    }

    function drawChart() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        const yStep = chartData.maxSpeed / 5;

        // 画坐标轴
        ctx.beginPath();
        ctx.moveTo(60, 10);
        ctx.lineTo(60, canvas.height - 40);
        ctx.lineTo(canvas.width - 10, canvas.height - 40);
        ctx.strokeStyle = '#000';
        ctx.lineWidth = 2;
        ctx.stroke();

        // Y轴刻度
        ctx.font = '12px Arial';
        ctx.fillStyle = '#000';
        for (let i = 0; i <= 5; i++) {
            const y = canvas.height - 40 - (i * (canvas.height - 50) / 5);
            ctx.fillText((i * yStep).toFixed(0), 20, y);
        }

        // 计算当前x轴间距
        const currentXSpacing = Math.max(
            chartData.minXSpacing,
            (canvas.width - 70) / chartData.speeds.length
        );

        // 绘制渐变区域
        if (chartData.speeds.length > 0) {
            ctx.beginPath();
            ctx.moveTo(60, canvas.height - 40);

            chartData.speeds.forEach((speedValue, index) => {
                const x = 60 + (index * currentXSpacing);
                const y = canvas.height - 40 - (speedValue * (canvas.height - 50) / chartData.maxSpeed);
                ctx.lineTo(x, y);
            });

            ctx.lineTo(60 + ((chartData.speeds.length - 1) * currentXSpacing), canvas.height - 40);

            const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
            gradient.addColorStop(0, 'rgba(59, 130, 246, 0.2)');
            gradient.addColorStop(1, 'rgba(59, 130, 246, 0)');
            ctx.fillStyle = gradient;
            ctx.fill();

            // 绘制折线
            ctx.beginPath();
            chartData.speeds.forEach((speedValue, index) => {
                const x = 60 + (index * currentXSpacing);
                const y = canvas.height - 40 - (speedValue * (canvas.height - 50) / chartData.maxSpeed);
                if (index === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            });

            ctx.strokeStyle = '#3B82F6';
            ctx.lineWidth = 2;
            ctx.stroke();

            // 绘制数据点
            chartData.speeds.forEach((speedValue, index) => {
                const x = 60 + (index * currentXSpacing);
                const y = canvas.height - 40 - (speedValue * (canvas.height - 50) / chartData.maxSpeed);
                ctx.beginPath();
                ctx.arc(x, y, 4, 0, Math.PI * 2);
                ctx.fillStyle = '#3B82F6';
                ctx.fill();
            });
        }

        // 绘制信号变化标记
        let lastSignal = null;
        chartData.signals.forEach((signal, index) => {
            if (signal !== lastSignal) {
                const x = 60 + (index * currentXSpacing);
                const y = canvas.height - 40 - (chartData.speeds[index] * (canvas.height - 50) / chartData.maxSpeed);
                drawSignalMarker(index, x, y, signal);
                lastSignal = signal;
            }
        });

        // 绘制悬停提示
        if (chartData.hoveredPoint !== null) {
            const index = chartData.hoveredPoint;
            const x = 60 + (index * currentXSpacing);
            const y = canvas.height - 40 - (chartData.speeds[index] * (canvas.height - 50) / chartData.maxSpeed);
            
            // 高亮显示当前点
            ctx.beginPath();
            ctx.arc(x, y, 6, 0, Math.PI * 2);
            ctx.fillStyle = '#FF4444';
            ctx.fill();
            
            drawTooltip(index, x, y);
        }

        chartData.animationFrameId = requestAnimationFrame(drawChart);
    }

    // 开始动画
    drawChart();

    // 清理函数
    function cleanup() {
        if (chartData.animationFrameId) {
            cancelAnimationFrame(chartData.animationFrameId);
        }
        canvas.removeEventListener('mousemove', handleMouseMove);
        canvas.removeEventListener('mouseleave', handleMouseLeave);
    }

    // 返回图表实例
    return {
        updateData: (newData) => {
            chartData.labels.push(newData.time);
            chartData.speeds.push(newData.speed);
            chartData.signals.push(newData.signal);
            chartData.positions.push(newData.position);

            chartData.maxSpeed = Math.max(
                chartData.maxSpeed,
                Math.max(...chartData.speeds)
            );

            // 保存更新后的数据
            saveData(chartData);
        },
        destroy: () => {
            cleanup();
        }
    };
}

export function updateChartData(chartInstance, newData) {
    chartInstance.updateData(newData);
}